package com.example.langchanin4jdemo1.controller;

import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.agent.tool.ToolSpecifications;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.output.Response;

import java.time.LocalDateTime;
import java.util.Arrays;

public class ToolDemo1 {
    @Tool("获取当前日期")
    public static String dateUtil(){
        return LocalDateTime.now().toString();
    }

    public static void main(String[] args) throws Exception{
        ChatLanguageModel model = QwenChatModel.builder()
                .apiKey("sk-875dd6ef14244431acdc7ccb974f5bfe")
                .modelName("qwen-max")
                .build();
        ToolSpecification toolSpecification = ToolSpecifications
                .toolSpecificationFrom(ToolDemo1.class.getMethod("dateUtil"));
        // 创建用户消息
        UserMessage userMessage = UserMessage.from("今天是几月几号");
        // 把用户消息和工具列表传递给大模型
        Response<AiMessage> aiMessageResponse = model.generate(Arrays.asList(userMessage), Arrays.asList(toolSpecification));
        // 第一次调用模型
        AiMessage aiMessage = aiMessageResponse.content();

        System.out.println("aiMessage"+"----------"+aiMessage);
//        aiMessage----------AiMessage { text = null toolExecutionRequests = [ToolExecutionRequest { id = "call_2c12c526babe4ddd90e6a6", name = "dateUtil", arguments = "{}" }] }

        // 判断是否有需要执行的工具
        if(aiMessage.hasToolExecutionRequests()){
            for(ToolExecutionRequest toolExecutionRequest : aiMessage.toolExecutionRequests()){
                String name = toolExecutionRequest.name();
                System.out.println(name+"name名字");
                // 利用反射执行工具
                Object result = ToolDemo1.class.getMethod(name).invoke(null);
                System.out.println(result);
                System.out.println(result+"result结果");
                // 创建工具执行的消息
                ToolExecutionResultMessage resultMessage = ToolExecutionResultMessage.from(toolExecutionRequest.id(), name, result.toString());
                // 生成新的ai响应，使用用户消息、原始 AI 消息和工具执行结果消息生成新的 AI 消息响应。
                Response<AiMessage> response = model.generate(Arrays.asList(userMessage, aiMessage, resultMessage));
                System.out.println(response.content().text());
            }
        }

    }

}
